<?php

namespace App\Http\Controllers\Resource;

use App\Http\Controllers\ElasticsearchServiceController;
use App\Models\ResourceQqrd;
use App\Models\ResourceTotal;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceYtys;
use App\Models\ResourceZwzx;
use Illuminate\Support\Facades\Log;

/**
 * 中文在线 数字资源
 */
class IndexController extends CommonController
{
    public $index_name = 'cqst_resource';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 创建es索引
     */
    public function createEsIndex()
    {
        // 获取 Elasticsearch 对象
        $es = new ElasticsearchServiceController();
        $res = $es->esCreateIndex($this->index_name);
        if ($res === true) {
            return $this->returnApi(200, '索引创建成功');
        } else {
            $res = is_string($res) ? $res : '索引创建失败';
            return $this->returnApi(202, $res);
        }
        // Log::channel('eslog')->debug('数据同步到ES完成');
    }

    /**
     * 同步数据到es
     * @param hour 0 表示不限制时间，全同步，其余表示 更改时间  单位小时
     */
    public function syncToEs()
    {
        $index_name = $this->index_name;
        $hour = $this->request->hour;
        // 获取 Elasticsearch 对象
        $es = new ElasticsearchServiceController();
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel::query()
            ->where('id', '>', 99)
            ->where(function ($query) use ($hour) {
                if ($hour) {
                    $query->where('change_time', '>', date('Y-m-d H:i:s', strtotime("-" . $hour . ' hours')));
                }
            })
            // 使用 chunkById 避免一次性加载过多数据
            ->chunkById(10, function ($data) use ($es, $index_name) {
                $start_msg = sprintf('正在同步 [ %s ] 表 ID 范围为 %s 至 %s 的数据', 'resource_total', $data->first()->id, $data->last()->id);
                //$this->info($start_msg); //$this->info() 输出信息到界面，跟echo 类似
                Log::channel('eslog')->debug($start_msg);
                $result_id = '';
                // 遍历商品
                foreach ($data as $i => $item) {

                    $param = [
                        'index' => $index_name,
                        'id' => $item->id,
                        'body' => [
                            'id' => $item->id,
                            'guid' => $item->guid,
                            'type_id' => $item->type_id,
                            'big_type_id' => $item->big_type_id,
                            'resource_business_id' => $item->resource_business_id,
                            'title' => $item->title,
                            'author' => $item->author,
                            'isbn' => $item->isbn,
                            'press' => $item->press,
                            'pre_time' => $item->pre_time,
                            'img' => $item->img,
                            'intro' => $item->intro,
                            'create_time' => str_replace(' ', 'T', $item->create_time->toArray()['formatted']) . 'Z', //$item->create_time  是一个对象  格式要求需要加 T  和 Z
                            'change_time' => str_replace(' ', 'T', $item->change_time->toArray()['formatted']) . 'Z',
                        ],
                    ];
                    try {
                        $is_exists = $es->esHasData($index_name, $item->guid);
                        if ($is_exists) {
                            //删除，ES 没有修改功能，都是删除
                            $es->esDataDelete($index_name, $item->id);
                        }

                        $es->getEsServiceObj()->index($param);
                    } catch (\Exception $e) {
                        //不处理报错
                        Log::channel('eslog')->debug('同步数据报错: ID-' . $item->id);
                        Log::channel('eslog')->debug($e->getMessage());
                    }

                    $result_id .= $item->id . '、';
                    trim($result_id);

                    // $param = [
                    //     'index' => 'ceshi5',
                    //     'id' => $item->id,
                    //     'body' => $item->toArray(),
                    // ];
                    // $datas[$i] = $param;
                }

                Log::channel('eslog')->debug('同步完成：' . $result_id);

                //  try {
                //      // 使用 bulk 方法批量创建
                //      $res = $es->bulk_doc2($datas, 'ceshi5');
                //  } catch (\Exception $e) {
                //      $this->error($e->getMessage());
                //      Log::channel('escmdlog')->debug($e->getMessage());
                //  }
                //  $this->info('同步完成' . $i);
            }, 'id');
        Log::channel('eslog')->debug('数据同步到ES完成');
    }

    /**
     * 检索 ES 数据 （全数据检索）
     * @param id 总表数据id
     */
    public function deleteEsData()
    {
        $id = $this->request->id;
        if (empty($keywords)) {
            return $this->returnApi(201, '检索条件不能为空');
        }

        $es = new ElasticsearchServiceController();
        try {
            //删除，ES 没有修改功能，都是删除
            $es->esDataDelete($this->index_name, $id);
        } catch (\Exception $e) {
            //不处理报错
            Log::channel('eslog')->debug('删除数据报错: ID-' . $id);
            Log::channel('eslog')->debug($e->getMessage());
        }
        return $this->returnApi(200, '删除数据成功');
    }

    /**
     * 删除 ES 索引
     * @param id 总表数据id
     */
    public function deleteEsIndex()
    {
        $es = new ElasticsearchServiceController();
        try {
            //删除，ES 没有修改功能，都是删除
            $es->deleteIndex($this->index_name);
        } catch (\Exception $e) {
            //不处理报错
            Log::channel('eslog')->debug('删除索引报错索引名: ' . $this->index_name);
            Log::channel('eslog')->debug($e->getMessage());

            return $this->returnApi(200, '删除索引失败');
        }
        return $this->returnApi(200, '删除索引成功');
    }


    /**
     * 检索 ES 数据 （全数据检索）
     * @param keywords 检索条件
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function searchEs()
    {
        $keywords = $this->request->keywords;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        if (empty($keywords)) {
            return $this->returnApi(201, '检索条件不能为空');
        }

        // 获取 Elasticsearch 对象
        $es = new ElasticsearchServiceController();
        $data = $es->esDataSearch($this->index_name, $keywords, $page, $limit);
        dump($data);
        die;
    }

    /**
     * 获取 ES 数据总量
     * @param keywords 检索条件
     */
    public function getSearchEsTotal()
    {
        $keywords = $this->request->keywords;
        // 获取 Elasticsearch 对象
        $es = new ElasticsearchServiceController();
        $data = $es->getSearchEsTotal($this->index_name, $keywords);
        dump($data);
        die;
    }

    /**
     * 检索 mysql 数据 （全数据检索）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function searchMysql()
    {
        $keywords = $this->request->keywords;
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        if (empty($keywords)) {
            return $this->returnApi(201, '检索条件不能为空');
        }

        $resourceTotalModel = new ResourceTotal();
        $res = $resourceTotalModel->lists($keywords, $resource_business_id, $big_type_id, null,null, null, null, null, null, null,null,$limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res);
    }



    /**
     * 图书检索接口(数据同步到数据库)
     * @param hour 同步多少小时内的数据 0 表示所有
     * @param page 10
     * @param limit 10
     * @param keywords 检索值
     */
    public function zwzxBookSearch()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $limit = $this->request->limit ? $this->request->limit : 10;
        $hour = $this->request->hour;
        $keywords = $this->request->keywords;
        $zwzxObj = new ZwzxController();
        if ($hour) {
            $modify = strtotime('-' . $hour . ' hour', time()) . '000'; //多获取一个小时的数据
        } else {
            $modify = null;
        }
        $res = $zwzxObj->bookSearch($modify, 1, $keywords, 1, 100); //计算总条数
        dump($res);
        die;
        $total = $res['totalCount'];
        $total_page = ceil($total / $limit);
        $resourceZwzxModel = new ResourceZwzx();
        for ($i = $page; $i <= $total_page; $i++) {
            $data = $zwzxObj->bookSearch($modify, 1, $keywords, $i, $limit);
            if ($data) {
                foreach ($data['list'] as $key => $val) {
                    $result = $resourceZwzxModel->addData($val);
                    echo $result . '、';
                }
            } else {
                Log::channel('zwzxlog')->debug('数据处理完毕: 页数: ' . $i . ' 每页条数: ' . $limit);
                return false;
            }
        }
    }

    /**
     * 获取图书目录
     * @param book_sh_id 图书 ShId
     * @param book_type 图书的 defaultType，PDF 或者 EPUB
     */
    public function zwzxGetBookCatalogue()
    {
        $book_sh_id = $this->request->book_sh_id;
        $book_type = $this->request->book_type;
        if (empty($book_sh_id) || empty($book_type)) {
            return $this->returnApi(201, '参数错误');
        }
        $zwzxObj = new ZwzxController();
        $res = $zwzxObj->getBookCatalogue($book_sh_id, $book_type); //计算总条数
        dump($res);
        die;
    }

    /**
     * 单点登录接口
     */
    public function zwzxSingleSign()
    {
        $user_id = $this->request->user_id;
        $redirect_url = $this->request->redirect_url;
        $book_type = $this->request->book_type;
        if (empty($user_id) || empty($redirect_url) || empty($book_type)) {
            return $this->returnApi(201, '参数错误');
        }

        $zwzxObj = new ZwzxController();
        $res = $zwzxObj->singleSign($user_id, $redirect_url, $book_type); //计算总条数
        dump($res);
        die;
    }

    /**
     * QQ阅读图书检索接口(数据同步到数据库)
     * @param page 10
     * @param limit 10
     * @param keywords 检索值
     */
    public function qqrdBookSync()
    {
        //先同步类型
        $qqrdObj = new QQrdController();
        $data_type = $qqrdObj->getBookType();
        if ($data_type) {
            $result_ids = '';
            foreach ($data_type['data'] as $key => $val) {
                $resourceTypeExternalModel = new ResourceTypeExternal();
                $val['parent_id'] = $val['parentid'];
                $val['level'] = $val['level'];
                $val['original_id'] = $val['id'];
                $val['resource_business_id'] = 2;
                $val['big_type_id'] = 1;
                $result_id = $resourceTypeExternalModel->getTypeNameNoAdd($val);


                $result_ids .= $result_id . '、';
                trim($result_id);
            }
            Log::channel('qqrdlog')->debug('QQ阅读数据类型同步完成: ' . $result_id);
        }
        $resourceQqrdModel = new ResourceQqrd();
        //获取数据上架列表
        $up_data = $qqrdObj->qqrdUpBookList(1); //获取总数据量
        if ($up_data) {
            for ($i = 1; $i <= $up_data['data']['maxPage']; $i++) {
                $data = $qqrdObj->qqrdUpBookList($i);
                if ($data) {
                    $result_id = '';
                    foreach ($data['data']['cbids'] as $key => $val) {
                        //获取数据详情
                        $up_data_info = $qqrdObj->getBookDetail($val);
                        if ($up_data_info) {
                            $result = $resourceQqrdModel->addData($up_data_info['data']);
                            $result_id .= $result . '、';
                        }
                    }
                    Log::channel('qqrdlog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                } else {
                    Log::channel('qqrdlog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                    return false;
                }
            }
        }

        //获取数据下架列表
        $down_data = $qqrdObj->qqrdDownBookList(1);
        if ($down_data) {
            //直接删除数据
            for ($i = 1; $i <= $down_data['data']['maxPage']; $i++) {
                $data = $qqrdObj->qqrdDownBookList($i);
                if ($data) {
                    $result_id = '';
                    foreach ($data['data']['cbids'] as $key => $val) {
                        $resourceQqrdModel = new ResourceQqrd();
                        $resourceQqrdModel->deleteData($val);
                        $result_id .= $val . '、';
                    }
                    Log::channel('qqrdlog')->debug('全量同步下架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                } else {
                    Log::channel('qqrdlog')->debug('全量同步下架数据处理完毕: 页数: ' . $i);
                    return false;
                }
            }
        }
    }


    /**
     * QQ阅读图书检索接口
     * @param page 10
     * @param limit 10
     * @param keywords 检索值
     */
    public function qqrdBookSearch()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $keywords = $this->request->keywords;

        if (empty($keywords)) {
            return $this->returnApi(201, '检索条件不能为空');
        }

        $qqrdObj = new QQrdController();
        $res = $qqrdObj->bookSearch($keywords, 1); //计算总条数
    }

    /**
     * QQ阅读获取图书基本信息
     * @param  bid String 书籍唯一标识
     */
    public function qqrdBookDetail()
    {
        $bid = $this->request->bid;
        if (empty($bid)) {
            return $this->returnApi(201, '参数错误');
        }
        $qqrdObj = new QQrdController();
        $res = $qqrdObj->getBookDetail($bid);
        dump($res);
        die;
    }

    /**
     * QQ阅读获取图书分类
     * @param  bid String 书籍唯一标识
     */
    public function qqrdBookType()
    {
        $qqrdObj = new QQrdController();
        $res = $qqrdObj->getBookType();
        dump($res);
        die;
        $total = $res['totalCount'];
        $total_page = ceil($total / $limit);
        $resourceZwzxModel = new ResourceZwzx();
        for ($i = $page; $i <= $total_page; $i++) {
            $data = $zwzxObj->bookSearch($modify, 1, $keywords, $i, $limit);
            if ($data) {
                foreach ($data['list'] as $key => $val) {
                    $result = $resourceZwzxModel->addData($val);
                    echo $result . '、';
                }
            } else {
                Log::channel('zwzxlog')->debug('数据处理完毕: 页数: ' . $i . ' 每页条数: ' . $limit);
                return false;
            }
        }
    }

    /**
     * 获得分类中书籍列表
     * @param page 10
     * @param type_id String 书籍唯一标识
     */
    public function qqrdTypeBookList()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $type_id = $this->request->type_id;
        if (empty($type_id)) {
            return $this->returnApi(201, '参数错误');
        }
        $qqrdObj = new QQrdController();
        $res = $qqrdObj->qqrdTypeBookList($type_id, $page);
        dump($res);
        die;
        $total = $res['totalCount'];
        $total_page = ceil($total / $limit);
        $resourceZwzxModel = new ResourceZwzx();
        for ($i = $page; $i <= $total_page; $i++) {
            $data = $zwzxObj->bookSearch($modify, 1, $keywords, $i, $limit);
            if ($data) {
                foreach ($data['list'] as $key => $val) {
                    $result = $resourceZwzxModel->addData($val);
                    echo $result . '、';
                }
            } else {
                Log::channel('zwzxlog')->debug('数据处理完毕: 页数: ' . $i . ' 每页条数: ' . $limit);
                return false;
            }
        }
    }

    /**
     * 获得所有已上架图书标识
     * @param page 10
     */
    public function qqrdUpBookList()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $qqrdObj = new QQrdController();
        $res = $qqrdObj->qqrdUpBookList($page);
        dump($res);
        die;
    }

    /**
     * 获得所有已下架图书标识
     * @param page 10
     */
    public function qqrdDownBookList()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $qqrdObj = new QQrdController();
        $res = $qqrdObj->qqrdDownBookList($page);
        dump($res);
        die;
    }



    /**
     * 云图有声图书检索接口(数据同步到数据库)
     * @param page 10
     * @param limit 10
     * @param keywords 检索值
     */
    public function ytysBookSync()
    {
        //先同步类型
        $obj = new YtysController();
        $data_type = $obj->getType();
        if ($data_type) {
            $result_ids = '';
            foreach ($data_type['data'] as $key => $val) {
                $resourceTypeExternalModel = new ResourceTypeExternal();
                $val['class_type_id'] = $val['classTypeId'];
                $val['parent_id'] = $val['parentId'];
                $val['parent_name'] = $val['parentName'];
                $val['resource_business_id'] = 3;
                $val['big_type_id'] = 2;
                $result_id = $resourceTypeExternalModel->getTypeNameNoAdd($val);

                $result_ids .= $result_id . '、';
                trim($result_id);
            }
            Log::channel('ytyslog')->debug('云图有声数据类型同步完成: ' . $result_id);
        }
        $obj = new YtysController();
        $book_type_relation = $obj->getBookTypeRelation();
        if ($book_type_relation) {
            $book_type_relation = array_column($book_type_relation['data'], 'classTypeId', 'bookId'); //获取书籍与类型的关系，类型为键值，书籍键名
        }

        $resourceModel = new ResourceYtys();
        //获取数据上架列表
        $up_data = $obj->getTypeBookList(1, 1); //获取总数据量
        if ($up_data) {
            $limit = 100;
            $total = $up_data['data']['totalRow'];
            $total_page = ceil($total / $limit);

            for ($i = 1; $i <= $total_page; $i++) {
                $data = $obj->getTypeBookList($i, $limit); //获取总数据量
                if ($data) {
                    $result_id = '';
                    foreach ($data['data']['list'] as $key => $val) {
                        //获取数据详情
                        $val['type_id'] = $book_type_relation[$val['bookId']] ?? null; //获取书籍小类
                        $result = $resourceModel->addData($val);
                        $result_id .= $result . '、';
                    }
                    Log::channel('ytyslog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                } else {
                    Log::channel('ytyslog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                    return false;
                }
            }
        }

        //获取数据下架列表
        $down_data = $obj->getSoldOut();
        if ($down_data) {
            //直接删除数据
            foreach ($down_data['data'] as $key => $val) {
                $resourceYtysModel = new ResourceYtys();
                $del_id = $resourceYtysModel->deleteData($val['bookId']);
                $result_id .= $del_id . '、';
            }

            Log::channel('ytyslog')->debug('全量同步下架数据，处理完毕: ' . $result_id);
        } else {
            Log::channel('ytyslog')->debug('暂无全量下架数据');
            return false;
        }
    }


    /**
     * 分类接口-根据父级编号获取下级分类
     *
     * classTypePid 备注：classTypePid =1469
     */
    public function ytysGetType()
    {
        $obj = new YtysController();
        $res = $obj->getType();
        dump($res);
        die;
    }


    /**
     * 分类接口-获取书籍分类的关系
     */
    public function ytysGetBookTypeRelation()
    {
        $obj = new YtysController();
        $res = $obj->getBookTypeRelation();
        dump($res);
        die;
    }

    /**
     * 书籍接口-获取分类下包含的书籍（分页）接口数据都是上架数据需进行剔除
     * @param  classTypeId
     * @param  sign MD5签名
     * @param  pageNum 页码
     * @param  pageSize 每页大小
     */
    public function ytysGetTypeBookList()
    {
        $page = $this->request->page ? $this->request->page : 1;
        $limit = $this->request->limit ? $this->request->limit : 10;
        $obj = new YtysController();
        $res = $obj->getTypeBookList($page, $limit);
        dump($res);
        die;
    }

    /**
     * 书籍接口-根据书籍编号获取书籍信息
     * @param  book_id 书籍id
     * @param  sign MD5签名
     */
    public function ytysGetBookInfoByBookId()
    {
        $book_id = $this->request->book_id;
        $obj = new YtysController();
        $res = $obj->getBookInfoByBookId($book_id);
        dump($res);
        die;
    }

    /**
     * 章节接口-根据书籍ID获取书籍章节信息（分页）
     * @param  book_id
     * @param  sign MD5签名
     * @param  pageNum 页码
     * @param  pageSize 每页大小
     */
    public function ytysGetBookCatalogue()
    {
        $book_id = $this->request->book_id;
        $page = $this->request->page ? $this->request->page : 1;
        $limit = $this->request->limit ? $this->request->limit : 10;
        $obj = new YtysController();
        $res = $obj->getBookCatalogue($book_id, $page, $limit);
        dump($res);
        die;
    }

    /**
     * 音频接口-获取章节有效的URL
     * @param  chapter_id
     * @param  sign MD5签名
     */
    public function ytysGetAudioInfo()
    {
        $chapter_id = $this->request->chapter_id;
        $obj = new YtysController();
        $res = $obj->getAudioInfo($chapter_id);
        dump($res);
        die;
    }

    /**
     * 获取全量下架资源
     */
    public function ytysGetSoldOut()
    {
        $obj = new YtysController();
        $res = $obj->getSoldOut();
        dump($res);
        die;
    }
}
